package edu.umn.msse.farside.FourH.web;

import com.dreamlizard.miles.beans.TimestampPropertyEditor;
import edu.umn.msse.farside.FourH.domain.Event;
import edu.umn.msse.farside.FourH.domain.Position;
import edu.umn.msse.farside.FourH.services.EventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;

/**
 * Created by IntelliJ IDEA.
 * User: corcutt
 * Date: Mar 21, 2009
 * Time: 9:56:34 AM
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/createPosition")
public class CreatePositionController
{
    private EventService eventService;
    private final PositionValidator positionValidator = new PositionValidator();

    @Autowired
    public void setEventService(EventService eventService)
    {
        this.eventService = eventService;
    }


    @InitBinder
    // bind timestamp type to a propertyeditor to properly create
    public void setAllowedFields(WebDataBinder dataBinder)
    {
        dataBinder.registerCustomEditor(Timestamp.class, new TimestampPropertyEditor());
        dataBinder.setRequiredFields(new String[]{"name", "description", "numberOfVolunteers"});
    }


    @RequestMapping(method = RequestMethod.GET)
    public String createPositionForm(@RequestParam(required = true) Long eventID, Model model, HttpSession session)
    {
        // eventID comes in on the request as a hidden parameter
        Position position = new Position();
        model.addAttribute("position", position);
        session.setAttribute("event", eventService.getEvent(eventID));

        return "createPosition";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String createPosition(@RequestParam(required = true) Long eventID, @ModelAttribute(value = "position") Position position, BindingResult result, HttpSession session)
    {
//        Event event = ((Event) session.getAttribute("event"));
        Event event = eventService.getEvent(eventID);
        positionValidator.validate(position, result, event);

        if (!result.hasErrors())
        {
            eventService.addPosition(event, position);
        }

        return result.hasErrors() ? "createPosition" : "redirect:editEvent?eventID=" + event.getId();

    }

}
